package com.qianyitian.hope2.analyzer.service;

import com.qianyitian.hope2.analyzer.analyzer.DemarkAnalyzer;
import com.qianyitian.hope2.analyzer.analyzer.IStockAnalyzer;
import com.qianyitian.hope2.analyzer.config.Constant;
import com.qianyitian.hope2.analyzer.model.*;
import com.qianyitian.hope2.analyzer.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

public class DemarkResultRunner {
    private Logger logger = LoggerFactory.getLogger(getClass());

    List<ResultInfo> selectResultList = null;
    IStockService stockService;
    List<Stock> symbols;
    String rehabType = Constant.EA_FUQUAN;
    DemarkAnalyzer demarkAnalyzer = new DemarkAnalyzer();

    public DemarkResultRunner(List<Stock> symbols, IStockService stockService) {
        this.stockService = stockService;
        this.symbols = symbols;
    }

    public List<Stock> getSymbols() {
        return symbols;
    }

    public AnalyzeResult getAnalyzeResult() {
        AnalyzeResult ar = new AnalyzeResult();
        ar.setResultList(selectResultList);
        ar.setGenerateTime(LocalDateTime.now().toString());
        return ar;
    }

    public void startAnalyze(String klineType) {
        selectResultList = new ArrayList<ResultInfo>();
        for (Stock stock : getSymbols()) {
            stock = getStock(stock.getCode(), klineType);
            if (stock != null) {
                ResultInfo resultInfo = analyze(stock);
                selectResultList.add(resultInfo);
            }
        }
    }

    public Stock getStock(String symbol, String klineType) {
        return stockService.getStock(symbol, rehabType, klineType);
    }

    private ResultInfo analyze(Stock stock) {
        ResultInfo resultInfo = new ResultInfo();
        resultInfo.setCode(stock.getCode());
        resultInfo.setName(stock.getName());
        //get stock url
        //http://quotes.money.163.com/0601899.html
        resultInfo.setUrl(Utils.convert163StockURL(stock.getCode()));
        try {
            boolean ok = demarkAnalyzer.analyze(resultInfo, stock);
            if (!ok) {
                //补上空的flag
                Map map = new HashMap<>(1);
                List<DemarkFlag> list = Collections.emptyList();
                map.put("flag", list);
                resultInfo.setData(map);
            }
        } catch (Exception e) {
            logger.error("DemarkResultRunner  stock " + stock.getCode(), e);
        }
        return resultInfo;
    }
}
